const { createOrUpdate, findCarts, updataCart, removeCart, selectAllCart, unselectAll } = require('../service/cart.service')
const { cartFormatError } = require('../constant/err.type')
class CartController {
    async add(ctx) {
        // 将商品添加到购物车
        const user_id = ctx.state.user.id
        const goods_id = ctx.request.body.goods_id
        console.log(user_id, goods_id);
        // 解析数据user_id,good_id,
        // 操作数据库
        const res = await createOrUpdate(user_id, goods_id)
        // 返回结果
        if (res) {
            ctx.body = {
                code: "200",
                message: "添加购物车成功",
                result: res
            }
        } else {

        }


    }

    async findAll(ctx) {
        // 解析请求参数
        const { pageNum = 1, pageSize = 10 } = ctx.request.query
        // 操作数据库
        const res = await findCarts(pageNum, pageSize)
        // 返回结果
        ctx.body = {
            code: "200",
            message: '获取购物车列表成功',
            result: res,
        }
    }

    async update(ctx) {
        // 解析参数
        const { id } = ctx.request.params
        const { number, selected } = ctx.request.body
        if (number === undefined && selected === undefined) {
            cartFormatError.message = 'number和selected不能同时为空'
            return ctx.app.emit('error', cartFormatError, ctx)
        }
        // 操作数据库
        const res = await updataCart({ id, number, selected })
        // 返回数据
        ctx.body = {
            code: "200",
            message: '更新购物车成功',
            result: res,
        }

    }

    async remove(ctx) {
        const { ids } = ctx.request.body
        const res = await removeCart(ids)

        ctx.body = {
            code: "200",
            message: '删除购物车成功',
            result: res,
        }
    }

    async selectAll(ctx) {
        const user_id = ctx.state.user.id
        const res = await selectAllCart(user_id)
        ctx.body = {
            code: "200",
            message: '全选成功',
            result: res,
        }
    }

    async unselectAll(ctx) {
        const user_id = ctx.state.user.id
        const res = await unselectAll(user_id)
        ctx.body = {
            code: "200",
            message: '取消全选成功',
            result: res,
        }
    }
}

module.exports = new CartController()